
  export class HubConnection {
    constructor() {
      this.openStatus = false;
      this.methods = {};
      this.negotiateResponse = {};
      this.connection = {};
      this.url = "";
      this.hub = "";
      this.invocationId = 0;
    }
    start(url, hub) {
      var negotiateUrl =url + "/negotiate?connectionData=%5B%7B%22name%22%3A%22"+hub+"%22%7D%5D&_=" + Date.parse(new Date())/1000;
     
      wx.request({
        url: negotiateUrl,
        method: "GET",
        async: false,
        success: res => {
          this.negotiateResponse = res.data;
          this.startSocket(url,hub);
        },
        fail: res => {
          console.error(`requrst ${url} error : ${res}`);
          return;
        }
      });
    }
    startSocket(url,hub) {
        let _url = url+"/connect?transport=webSockets&clientProtocol=1&connectionToken="+encodeURIComponent(this.negotiateResponse.ConnectionToken)+"&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D"
      _url = _url.replace(/^http/,"ws");
      this.connecturl = _url;
      this.url = url;
      this.hub = hub;
      if (this.connection != null && this.openStatus) {
        return;
      }
  
  
      this.connection = wx.connectSocket({
        url: this.connecturl
      })
  
      this.connection.onOpen(res => {
        console.log(`websocket 链接: ${this.connecturl}`);
        this.openStatus = true;
        this.onOpen(res);

        let startUrl = this.url + "/start?transport=webSockets&connectionToken="+encodeURIComponent(this.negotiateResponse.ConnectionToken)+"&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=" + Date.parse(new Date())/1000 + "&openid=111";
        wx.request({
            url: startUrl,
            method:"GET",
            success:res => {
            //console.log(res.data);
            }
        })
      });
      this.connection.onClose(res => {
        console.log('连接关闭');
        this.connection = null;
        this.openStatus = false;
        this.onClose(res);
      });
      this.connection.onError(res => {
        console.error(`websocket error msg: ${msg}`);
        this.close({
          reason: msg
        });
        this.onError(res)
      });
      this.connection.onMessage(res => this.receive(res));
    }
on(method, fun) {

    let methodName = method.toLowerCase();
    if (this.methods[methodName]) {
        this.methods[methodName].push(fun);
    } else {
        this.methods[methodName] = [fun];

    }
    }
    onOpen(data) {}
    onClose(msg) {}
    onError(msg) {}
  
  
    close(data) {
      if(this.openStatus == true)
      {
        if (data) {
            this.connection.close(data);
          } else {
            this.connection.close();
          }
          this.openStatus = false;
      }
      else{
        console.log('连接关闭');
      }
    }
  
    receive(data) {
      if (data.data.length > 3) {
        data.data = data.data.replace('{}', "")
      }
      var message = JSON.parse(data.data);
     
      var C = message.C;
      var M = message.M;
      if(M!=undefined && M.length>0)
      {
          var resmessage = M[0];
        this.invokeClientMethod(resmessage);
      }
     
    }
  
  
    // send(functionName) {
  
    //   var args = [];
    //   for (var _i = 1; _i < arguments.length; _i++) {
    //     args[_i - 1] = arguments[_i];
    //   }
    //   this.invocationId++;
    // }
  
  
    invoke(functionName) {
      if( this.openStatus==false)
      {
        console.log('连接关闭');
        return;
      }
      var args = [];
    
      for (var _i = 1; _i < arguments.length; _i++) {
        args[_i - 1] = arguments[_i];
      }
  
      var data = { H: this.hub, M: functionName, A: args, I: this.invocationId };
    wx.sendSocketMessage({
      data:JSON.stringify(data)
    })
     this.invocationId++;
    }
  
    invokeClientMethod(message) {
        var resH = message.H;
        var resM = message.M;
        var resA = message.A;
      if(resH.toLowerCase() == this.hub.toLowerCase())
      {
        var methods = this.methods[resM.toLowerCase()];
        console.log(methods);
        if (methods) {
          methods.forEach(m => m.apply(this, resA));
          if (resA.length==0) {
            var errormsg = "没有参数";
            console.error(errormsg);
            this.close({
              reason: errormsg
            });
          }
        } else {
          console.warn(`No client method with the name '${message.target}' found.`);
        }
      }
      else{
        console.warn(`Hub is wrong`);
      }
      
    }
  }